import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import axios from 'axios';
import { FaArrowLeft, FaExternalLinkAlt, FaUserAlt, FaExchangeAlt, FaHistory } from 'react-icons/fa';
import '../styles/PersonnelDetail.css';

const PersonnelDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [personnel, setPersonnel] = useState(null);
  const [positionChangelogs, setPositionChangelogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('profile');

  // 获取人员详情和职位变更日志
  useEffect(() => {
    const fetchPersonnelDetail = async () => {
      try {
        setLoading(true);
        const res = await axios.get(`/api/personnel/${id}`);
        setPersonnel(res.data.personnel);
        setPositionChangelogs(res.data.positionChangelogs || []);
        setError(null);
      } catch (err) {
        console.error('获取人员详情失败:', err);
        setError(err.response?.data?.message || '获取人员详情失败');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchPersonnelDetail();
    }
  }, [id]);

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  if (!personnel) {
    return <div className="error-message">人员不存在或已被删除</div>;
  }

  // 格式化变更类型
  const formatChangeType = (type) => {
    const typeMap = {
      'appointed': '任命',
      'replaced': '被替换',
      'transferred': '调动',
      'promoted': '升职',
      'demoted': '降职',
      'retired': '退休',
      'resigned': '辞职'
    };
    
    return typeMap[type] || type;
  };

  // 获取完整数据中的传记信息
  const getBiographyFromFullDetails = () => {
    if (personnel.fullDetails) {
      // 尝试从fullDetails中获取biography字段
      if (personnel.fullDetails.biography) {
        return personnel.fullDetails.biography;
      }
      
      // 查找可能包含biography的字段
      for (const [key, value] of Object.entries(personnel.fullDetails)) {
        if (typeof value === 'object' && value?.biography) {
          return value.biography;
        }
      }
    }
    return null;
  };

  // 清理传记内容，移除无效信息和规范化空行
  const cleanBiographyText = (text) => {
    if (!text) return '';
    
    // 移除特定的无效标记
    const invalidMarkers = ['Download', 'Share', 'PRINT', 'RSS'];
    let cleaned = text;
    
    invalidMarkers.forEach(marker => {
      cleaned = cleaned.replace(new RegExp(marker, 'gi'), '');
    });
    
    // 更强力地处理连续空行 - 使用正则表达式清理任何包含多于一个连续空行的情况
    cleaned = cleaned.replace(/\n\s*\n\s*\n+/g, '\n\n');
    
    // 删除只包含空格的行
    cleaned = cleaned.replace(/\n\s+\n/g, '\n\n');
    
    // 移除前后多余空白
    cleaned = cleaned.trim();
    
    // 检测并移除重复的标题/职位描述
    // 例如："Executive Director, Total Force Management"这样的文本如果连续重复出现
    const lines = cleaned.split('\n');
    const uniqueLines = [];
    let prevLine = '';
    
    for (let i = 0; i < lines.length; i++) {
      const currentLine = lines[i].trim();
      // 跳过空行和与前一非空行相同的行
      if (currentLine && currentLine !== prevLine) {
        uniqueLines.push(currentLine);
        prevLine = currentLine;
      } else if (!currentLine) {
        // 保留空行，但不更新prevLine
        uniqueLines.push('');
      }
    }
    
    // 重新组合文本，确保没有连续的空行
    let result = '';
    let emptyLineAdded = false;
    
    for (let i = 0; i < uniqueLines.length; i++) {
      if (uniqueLines[i]) {
        if (result && (emptyLineAdded || result.endsWith('\n'))) {
          result += uniqueLines[i];
        } else if (result) {
          result += '\n\n' + uniqueLines[i];
        } else {
          result = uniqueLines[i];
        }
        emptyLineAdded = false;
      } else if (!emptyLineAdded && result) {
        // 只添加一个空行
        result += '\n\n';
        emptyLineAdded = true;
      }
    }
    
    return result;
  };

  // 格式化结构化信息中的复杂值
  const formatStructuredValue = (value) => {
    if (value === null || value === undefined) {
      return '-';
    }
    
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
      return String(value);
    }
    
    if (Array.isArray(value)) {
      if (typeof value[0] === 'string' || typeof value[0] === 'number') {
        return (
          <ul className="structured-list">
            {value.map((item, index) => <li key={index}>{String(item)}</li>)}
          </ul>
        );
      } else if (typeof value[0] === 'object') {
        return (
          <div className="nested-objects">
            {value.map((item, index) => (
              <div key={index} className="nested-object">
                <table className="nested-table">
                  <tbody>
                    {Object.entries(item).map(([nestedKey, nestedValue]) => (
                      <tr key={nestedKey}>
                        <td className="nested-key">{nestedKey}</td>
                        <td className="nested-value">{formatStructuredValue(nestedValue)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ))}
          </div>
        );
      }
    }
    
    if (typeof value === 'object') {
      return (
        <table className="nested-table">
          <tbody>
            {Object.entries(value).map(([nestedKey, nestedValue]) => (
              <tr key={nestedKey}>
                <td className="nested-key">{nestedKey}</td>
                <td className="nested-value">{formatStructuredValue(nestedValue)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      );
    }
    
    return JSON.stringify(value);
  };

  // 来自完整数据的传记
  const biographyFromFullDetails = getBiographyFromFullDetails();

  return (
    <div className="personnel-detail-container">
      <div className="page-header">
        <button onClick={() => navigate('/personnel')} className="back-button">
          <FaArrowLeft /> 返回列表
        </button>
        <h1>人员详情</h1>
      </div>

      <div className="personnel-info-container">
        {/* 基本信息 */}
        <div className="basic-info-card">
          <div className="profile-header">
            {personnel.imageUrl ? (
              <img 
                src={personnel.imageUrl} 
                alt={personnel.name} 
                className="profile-image" 
              />
            ) : (
              <div className="profile-image-placeholder">
                <FaUserAlt />
              </div>
            )}
            <div className="profile-title">
              <h2>{personnel.name}</h2>
              <div className="profile-subtitle">
                <span className="position">{personnel.position || '未知职位'}</span>
                <span className="organization">{personnel.organization}</span>
              </div>
              {personnel.positionChangeStatus && (
                <span className={`position-status position-status-${personnel.positionChangeStatus}`}>
                  <FaExchangeAlt className="status-icon" />
                  {personnel.positionChangeStatus === 'new' ? '新任命' :
                   personnel.positionChangeStatus === 'replaced' ? '被替换' :
                   personnel.positionChangeStatus === 'replacement' ? '接替者' : '职位变动'}
                </span>
              )}
            </div>
          </div>
          
          <div className="info-divider"></div>
          
          <div className="info-rows">
            <div className="info-row">
              <span className="info-label">首次发现:</span>
              <span className="info-value">{new Date(personnel.firstDetected).toLocaleString()}</span>
            </div>
            <div className="info-row">
              <span className="info-label">最后更新:</span>
              <span className="info-value">{new Date(personnel.lastUpdated).toLocaleString()}</span>
            </div>
            {personnel.positionChangeDate && (
              <div className="info-row">
                <span className="info-label">职位变更日期:</span>
                <span className="info-value">{new Date(personnel.positionChangeDate).toLocaleString()}</span>
              </div>
            )}
            <div className="info-row">
              <span className="info-label">数据源:</span>
              <span className="info-value">{personnel.sourceId?.name || '未知'}</span>
            </div>
            {personnel.detailUrl && (
              <div className="info-row">
                <span className="info-label">详情链接:</span>
                <a 
                  href={personnel.detailUrl} 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="external-link"
                >
                  访问链接 <FaExternalLinkAlt size={12} />
                </a>
              </div>
            )}
          </div>
        </div>

        {/* 内容标签页 */}
        <div className="detail-tabs">
          <button 
            className={`tab-button ${activeTab === 'profile' ? 'active' : ''}`}
            onClick={() => setActiveTab('profile')}
          >
            人员简介
          </button>
          <button 
            className={`tab-button ${activeTab === 'structured' ? 'active' : ''}`}
            onClick={() => setActiveTab('structured')}
          >
            结构化信息
          </button>
          <button 
            className={`tab-button ${activeTab === 'changes' ? 'active' : ''}`}
            onClick={() => setActiveTab('changes')}
          >
            职位变更记录
          </button>
        </div>

        {/* 简介信息 */}
        {activeTab === 'profile' && (
          <div className="tab-content">
            {/* 传记信息 - 优先使用fullDetails中的biography */}
            {personnel.fullDetails?.biography && (
              <div className="detail-card">
                <h3>传记</h3>
                <div className="biography">
                  {cleanBiographyText(personnel.fullDetails.biography)}
                </div>
              </div>
            )}
            
            {/* 如果fullDetails中没有biography，但有biographyFromFullDetails */}
            {!personnel.fullDetails?.biography && biographyFromFullDetails && (
              <div className="detail-card">
                <h3>传记</h3>
                <div className="biography">
                  {cleanBiographyText(biographyFromFullDetails)}
                </div>
              </div>
            )}
            
            {/* 如果fullDetails和biographyFromFullDetails都没有，但有独立的biography字段 */}
            {!personnel.fullDetails?.biography && !biographyFromFullDetails && personnel.biography && (
              <div className="detail-card">
                <h3>传记</h3>
                <div className="biography">
                  {cleanBiographyText(personnel.biography)}
                </div>
              </div>
            )}

            {/* 如果fullDetails中有role字段，将其显示为角色描述 */}
            {personnel.fullDetails?.role && (
              <div className="detail-card">
                <h3>角色描述</h3>
                <div className="role-description">
                  {personnel.fullDetails.role}
                </div>
              </div>
            )}

            

            {/* 快照 - 仅当没有更好的数据源时显示 */}
            {!personnel.detailPageContent && personnel.detailPageSnapshot && (
              <div className="detail-card">
                <h3>页面快照</h3>
                <div className="snapshot-container">
                  <iframe 
                    src={`data:text/html;charset=utf-8,${encodeURIComponent(personnel.detailPageSnapshot)}`}
                    title="页面快照"
                    className="snapshot-iframe"
                  />
                </div>
              </div>
            )}

            {!personnel.fullDetails?.biography && !biographyFromFullDetails && !personnel.biography && 
             !personnel.fullDetails?.role && !personnel.detailPageContent && !personnel.detailPageSnapshot && (
              <div className="detail-card empty-card">
                <p>暂无详细人员简介信息</p>
              </div>
            )}
          </div>
        )}

        {/* 结构化信息 */}
        {activeTab === 'structured' && (
          <div className="tab-content">
            {personnel.fullDetails?.structuredInfo && Object.keys(personnel.fullDetails.structuredInfo).length > 0 ? (
              <div className="detail-card">
                <h3>结构化信息</h3>
                <table className="structured-table">
                  <tbody>
                    {Object.entries(personnel.fullDetails.structuredInfo).map(([key, value]) => (
                      <tr key={key}>
                        <td className="structured-key">{key.replace(/_/g, ' ')}</td>
                        <td className="structured-value">
                          {formatStructuredValue(value)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : personnel.structuredInfo && Object.keys(personnel.structuredInfo).length > 0 ? (
              <div className="detail-card">
                <h3>结构化信息</h3>
                <table className="structured-table">
                  <tbody>
                    {Object.entries(personnel.structuredInfo).map(([key, value]) => (
                      <tr key={key}>
                        <td className="structured-key">{key.replace(/_/g, ' ')}</td>
                        <td className="structured-value">
                          {formatStructuredValue(value)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="detail-card empty-card">
                <p>暂无结构化信息</p>
              </div>
            )}
          </div>
        )}

        {/* 职位变更历史 */}
        {activeTab === 'changes' && (
          <div className="tab-content">
            {positionChangelogs.length > 0 ? (
              <div className="detail-card">
                <h3>职位变更历史</h3>
                <div className="position-changelogs">
                  {positionChangelogs.map(log => (
                    <div key={log._id} className="position-changelog-item">
                      <div className="changelog-header">
                        <span className={`changelog-type changelog-${log.changeType}`}>
                          <FaHistory className="changelog-icon" />
                          {formatChangeType(log.changeType)}
                        </span>
                        <span className="changelog-time">
                          {new Date(log.timestamp).toLocaleString()}
                        </span>
                      </div>
                      
                      <div className="position-change-details">
                        {log.previousPosition && (
                          <div className="position-change-field">
                            <span className="field-label">原职位:</span>
                            <span className="field-value">{log.previousPosition}</span>
                          </div>
                        )}
                        {log.newPosition && (
                          <div className="position-change-field">
                            <span className="field-label">新职位:</span>
                            <span className="field-value">{log.newPosition}</span>
                          </div>
                        )}
                        {log.previousOrganization && (
                          <div className="position-change-field">
                            <span className="field-label">原组织:</span>
                            <span className="field-value">{log.previousOrganization}</span>
                          </div>
                        )}
                        {log.newOrganization && (
                          <div className="position-change-field">
                            <span className="field-label">新组织:</span>
                            <span className="field-value">{log.newOrganization}</span>
                          </div>
                        )}
                        {log.relatedPersonnel && log.relatedPersonnel.length > 0 && (
                          <div className="related-personnel">
                            <span className="field-label">相关人员:</span>
                            <ul className="related-list">
                              {log.relatedPersonnel.map(related => (
                                <li key={related._id}>
                                  <Link to={`/personnel/${related._id}`}>
                                    {related.name} ({related.relationship})
                                  </Link>
                                </li>
                              ))}
                            </ul>
                          </div>
                        )}
                        {log.reason && (
                          <div className="position-change-field">
                            <span className="field-label">变更原因:</span>
                            <span className="field-value">{log.reason}</span>
                          </div>
                        )}
                        {log.details && (
                          <div className="position-change-field">
                            <span className="field-label">详细说明:</span>
                            <span className="field-value">{log.details}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="detail-card empty-card">
                <p>暂无职位变更记录</p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default PersonnelDetail; 